package com.example.springboot.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.entity.Equipment;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.EquipmentMapper;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service//注入到spring容器中
public class EquipmentService extends ServiceImpl<EquipmentMapper, Equipment> {
    public Equipment getByName(String name) {
        QueryWrapper<Equipment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        return baseMapper.selectOne(queryWrapper);
    }

    public void updateByName(String name, BigDecimal useCount) {
        Equipment equipment = getByName(name);
        if (equipment != null) {
            BigDecimal newCount = equipment.getCount().subtract(useCount);
            if (newCount.compareTo(BigDecimal.ZERO) < 0) {
                newCount = BigDecimal.ZERO;
            }
            equipment.setCount(newCount);
            baseMapper.updateById(equipment);
        } else {
            throw new RuntimeException("未找到名称为 " + name + " 的设备");
        }
    }
}
